import React, { useState } from 'react'
import Taro from '@tarojs/taro'
import { AtForm, AtInput, AtButton, AtMessage } from 'taro-ui'
import { View } from '@tarojs/components'
import { request } from '@/utils'
import './index.less'

const Login = () => {
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const handlePhoneChange = (e) => {
    if (e.length <= 13) {
      setPhone(e)
    }
  }
  const handlePasswordChange = (e) => {
    setPassword(e)
  }
  const handleSubmit = async () => {
    if (!phone) {
      Taro.atMessage({  message: '请输入账号', type: 'error' })
      return
    }
    if (!password) {
      Taro.atMessage({ message: '请输入密码', type: 'error' })
      return
    }
    Taro.showLoading({mask: true})
    const openId = Taro.getStorageSync('openId')
   const {token, error} = await request({url: 'hkshihua/user/doLogin', data: {account: phone,
    pwd: password,openId,
    source: '0'}})
    if(error) return
   const res = await request({url: 'hkshihua/user/getAllprofile', header: {token}})
   if(res.error) return
   Taro.setStorage({key: 'userInfo', data: JSON.stringify({token, user: res.authUser})}).then(() => {
     console.log(Taro.getCurrentInstance().page.getTabBar());
    // Taro.getCurrentPages()[0].getTabBar().setData({
    //   list: ALLTABS[res.authUser.role]
    // })
    if(res.authUser.role == 'OPERATOR') {
      Taro.switchTab({url: '/pages/scanQRCode/index'})
    } else {
      Taro.switchTab({url: '/pages/index/index'})
    }
    console.log(Taro.getCurrentInstance().page.getTabBar());
   })
  }

  return <AtForm className='login'>
    <AtMessage />
    <View className='content'>
      <View className='title'>优惠加油</View>
      <View className='phone'>
        <AtInput cursor={-1} placeholderStyle='color: #fff' maxLength={13} name='phone' type='text' placeholder='请输入账号' value={phone} onChange={handlePhoneChange} />
      </View>
      <View className='pass'>
        <AtInput cursor={-1} placeholderStyle='color: #fff' name='password' type='password' placeholder='请输入密码' value={password} onChange={handlePasswordChange} />
      </View>
      <View className='btn'>
        <AtButton circle  type='primary' onClick={handleSubmit}>登录</AtButton>
      </View>
    </View>
  </AtForm>
}

export default Login
